package protocol.transactions;

import java.lang.reflect.Type;
import java.util.List;

import protocol.XoneProtocol;
import protocol.XoneServiceCode;
import protocol.meta.AppInfo;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.netease.http.THttpRequest;
import com.netease.pkgRelated.XoneConsts;

import db.manager.ManagerAppInfo;


public class TransactionGetTopicInfoList extends XoneBaseTransaction {

    private long mTopicId;
    private int mCurrentPage;
    private int mPageSize;


    public TransactionGetTopicInfoList(long topicId, int currentPage ,int pageSize) {
        super(TRANSACTION_TYPE_GET_TOPIC_INFO_LIST);
        mTopicId = topicId;
        mCurrentPage = currentPage;
        mPageSize = pageSize;
    }

    @Override
    protected void onXoneTransactionSuccess(int code, Object obj) {
        if (obj instanceof JsonElement) {
            boolean hasMore = false;
            try {
                JsonElement array = ((JsonElement)obj).getAsJsonObject().get("list");
                Gson gson = new Gson();
                List<AppInfo> list = null;
                Type collectionType = new TypeToken<List<AppInfo>>(){}.getType();
                list = gson.fromJson(array, collectionType);
                if(list != null && list.size() == XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT){
                    hasMore = true;
                }
                if(mCurrentPage == 1){
                    //需要清除老数据
                    ManagerAppInfo.delete(ManagerAppInfo.GROUP_TOPIC_INFO_LIST, Long.valueOf(mTopicId));
                }
                if (0 < list.size()) {
                    ManagerAppInfo.replaceAppInfo(ManagerAppInfo.GROUP_TOPIC_INFO_LIST, Long.valueOf(mTopicId), list);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            notifyMessage(XoneServiceCode.TRANSACTION_SUCCESS, hasMore);
        }else{
            notifyError(XoneServiceCode.TRANSACTION_FAIL, null);
        }
    }

    @Override
    public void onTransact() {
        THttpRequest request = XoneProtocol.getInstance().createGetTopicInfoList(mTopicId,mCurrentPage,mPageSize);
        sendRequest(request);
    }
}
